package com.yf.mq;

import com.rabbitmq.client.Channel;
import com.yf.config.constant.RabbitConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;

/*********************************************************
 **
 ** <br><br>
 ** @ClassName: CommonConsume
 ** @author: yangfeng
 ** @date: 2024/11/16 18:21
 ** @version: 1.0.0
 *********************************************************/
@Component
@Slf4j
public class CommonConsume {
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = RabbitConstant.DIRECT_HELLO_QUEUE, durable = "true"),
            exchange = @Exchange(name = RabbitConstant.COMMON_DIRECT_EXCHANGE, durable = "false", type = "direct"),
            key = {RabbitConstant.DIRECT_HELLO_ROUTING_KEY}
    ))
    public void hello1(String msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag)throws IOException{
        try {
            log.info("收到direct hello 的消息 {}",msg);
            channel.basicAck(deliveryTag,true);
        } catch (Exception e) {
            log.error("consumer-direct hello：{}，数据:{}",e.getMessage(), msg);
            //requeue:true为将消息重返当前消息队列,还可以重新发送给消费者;false:将消息丢弃
            channel.basicNack(deliveryTag, false, false);
        }
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delay.queue", durable = "true"),//创建队列（durable参数：队列要不要持久化）
            exchange = @Exchange(name = RabbitConstant.COMMON_DELAY_EXCHANGE, type = ExchangeTypes.DIRECT, delayed = "true"),//创建交换机。delayed=true:该交换机是延迟交换机，可以接收延迟消息
            key = "hi" //RoutingKey 可以写多个，也可以写一个
    ))
    public void listenDelayQueue(String msg, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        try {
            log.info("消息 {} 消费时间为 {}",msg, LocalDateTime.now());
            channel.basicAck(deliveryTag,true);
        } catch (Exception e) {
            channel.basicNack(deliveryTag, false, false);
            throw new RuntimeException(e);
        }
    }
}
